﻿require.config({
  urlArgs: "version=20170407",
  paths: {
    'jquery': 'packages/jquery-2.14-min',
    'mousewheel': 'packages/jquery.mousewheel',
    //'jqueryform': 'packages/jquery-form',
    'bootstrap': '../bootstrap/js/bootstrap.min',
    'bootfileinput':'../bootstrap/bootstrap-fileinput/js/fileinput.min',
    'amazeui':'../js/amazeui'
  },
  shim: {
    'bootstrap': {
      deps: ['jquery'],
      exports: 'bootstrap'
    }
  }
  
});

require(['jquery','mousewheel','bootstrap','bootfileinput','amazeui'], function ($) {
	 tinymce.init({
		  selector: "textarea#Content",  
		  language : 'zh_CN',  
		  theme: "modern",  
		  height: 300,
		  plugins: [
		    	    'advlist autolink lists link image charmap print preview hr anchor pagebreak',
		    	    'searchreplace visualblocks visualchars code fullscreen',
		    	    'insertdatetime media nonbreaking save table contextmenu directionality',
		    	    'emoticons template paste textcolor colorpicker textpattern imagetools',
		    	  ],
		  content_css: "../../css/content.css",  
		  toolbar1: 'styleselect | bold italic | bullist numlist outdent indent | link image |print preview media | forecolor backcolor emoticons | sizeselect | fontselect |  fontsizeselect |',
		  
		  file_browser_callback: function(field_name, url, type, win) {
			 //if(type=='image') $('#m_form input').click();
			 uploadwin();
			 $("#newImage").click();
		  },
		 relative_urls : false,
		 remove_script_host : true,
		 //document_base_url : "../../",
		 convert_urls : true, 
		  
		 fontsize_formats: "8pt 10pt 12pt 14pt 18pt 20pt 24pt 30pt 36pt 48pt 60pt",
		 style_formats_merge: true,
		 style_formats: [
		                { title: '宋体', inline: 'span', styles: { 'font-family':'宋体'}  },
		                { title: '黑体', inline: 'span', styles: { 'font-family':'黑体'}  },
		                { title: '楷体', inline: 'span', styles: { 'font-family':'楷体'}  },
		                { title: '微软雅黑', inline: 'span', styles: { 'font-family':'Microsoft Yahei'} },
		              ]
	  });
	 
	 
	 var _jm=null;
	 var changenode={};
	 var maxid="0";
	 var linkmsg="new link";
	 var fromid="";
	 var toid="";
	 var rootName;
	 var alldate;
	 var selfid;
	 var account_id=0;
	 var account_name="";
	 var currentPosition,timer;
	 var role_type="";
	 var treeshow_bool=false;
	 
  if(window.location.pathname=='/admin/selfpmctreat.html'){
	  $.ajax({
		  type: 'GET',
		  url: '/terms/searchrelate/draw',
		  cache :false,
		  data:{
			  'depth':9
		  },
	    	//timeout:7000,//请求超时后停止请求
	    	//dataType : 'json',
	    	success: function (res) {
	    		if (res.status == 200) {
	    			
	    			drawGraph(res.data);
	    			
	    			for(var num in res.data){
	    				if(parseInt(res.data[num].id)>parseInt(maxid)){
	    					maxid=res.data[num].id;
	    				}
	    			}
	    			
	    		}else{
	    			alert("加载失败");
	    			window.location.href = "/admin/selfplib.html";
	    		}
	    	},
	    	error: function (xml, err, throwInfo) {
	    		alert(err);
	    	}
	  });
  }
  if(window.location.pathname=='/admin/selfpmtreat.html'){
	  $.ajax({
		  type: 'GET',
		  url: '/terms/search/draw',
		  cache :false,
		  data:{
			  'depth':9
		  },
	    	//timeout:7000,//请求超时后停止请求
	    	//dataType : 'json',
	    	success: function (res) {
	    		if (res.status == 200) {
	    			drawGraph(res.data);
	        
	    			for(var num in res.data){
	    				if(parseInt(res.data[num].id)>parseInt(maxid)){
	    					maxid=res.data[num].id;
	    				}
	    			}
	    			
	    		}else{
	    			alert("加载失败");
	    			window.location.href = "/admin/selfplib.html";
	    		}
	    	},
	    	error: function (xml, err, throwInfo) {
	    		alert(err);
	    	}
	  });
  	}
	if(window.location.pathname=='/admin/selfpptreat.html'){
		 $.ajax({
			    type: 'GET',
			    url: '/schems/search/draw',
			    cache :false,
			    //timeout:7000,//请求超时后停止请求
			    //dataType : 'json',
			    success: function (res) {
			      if (res.status == 200) {
			    	  alldate=res.data;
			    	  var jsondta=eval("(" + res.data.content + ")");  
			    	  rootName=res.data.root;
			    	  document.getElementById("secondbread").innerText = rootName;
			    	  selfid=res.data.id;
			    	  for (var num in jsondta.data){
			    		  if(jsondta.data[num].id>maxid){
			    			  maxid=jsondta.data[num].id;
			    		  }
			    	  }
			    	
			    	drawPGraph(jsondta);
			    	
			    	
			      }else{
			        alert("加载失败");
			        window.location.href = "/admin/selfplib.html";
			      }
			    },
			    error: function (xml, err, throwInfo) {
			      alert(err);
			    }
		  });
	}
	$.ajax({
		type : 'POST',
		url : '/users/getId',
		//data : jsonda,
	    cache: false,
		async:false,
		//contentType: "application/json; charset=utf-8",
		dataType : 'json',
		success : function(res) {
			if (res.status == 200) {
				//循环遍历json，并将其加入显示中
			
					account_id=res.data.id;
					account_name=res.data.name;
					document.getElementById("user-info").innerHTML="&nbsp"+res.data.name;
					if(res.data.role=="[admin, user]"){
						role_type="[admin, user]";
						$('#searchback')[0].setAttribute("href","/admin/selfplib.html");
					}
					//alert(res.data.name);
			
				
			} else
				alert("加载失败！");
		},
		error : function(xml, err, throwInfo) {
			alert(err);
		}
	});	
 
  
	$('#jsmind_container').css('height',$(window).height()-$("#jsmind_container").offset().top+'px');
	$('#jsmind_container_search').css('height',$(window).height()-$("#jsmind_container").offset().top+'px');
  	$('#jsmind_container_search').css('margin-top','-'+$('#jsmind_container').css('height'));
  	var fx=$('#jsmind_container').width();
	var fy=$('#jsmind_container').height();
	
  	//selfresize();
	$('#user-info').mouseover(function(){
		document.getElementById("user-info").innerHTML="&nbsp"+"退出登录";
	});
	$('#user-info').mouseleave(function(){
		document.getElementById("user-info").innerHTML="&nbsp"+account_name;
	});
	$("#revoke").click(function(){
			_jm.pop_revoke();
			//document.body.removeChild(document.getElementsByClassName('mce-tinymce mce-container mce-panel')[0]);
	});
	$('#show-tree').click(function(event){
    	if(!treeshow_bool){
    		$('#mindmap-tool-win')[0].style.display="block";
    		$('#jsmind_container')[0].style.marginTop="100px";
    		
    		treeshow_bool=true;
    	}else{
    		$('#mindmap-tool-win')[0].style.display="";
    		$('#jsmind_container')[0].style.marginTop="60px";
    		treeshow_bool=false;
    	}
    });
	$('#user-logout').click(function(){
		$.ajax({
			type : 'GET',
			url : '/logout',
			//data : jsonda,
		    cache: false,
			async: false,
			//contentType: "application/json; charset=utf-8",
			dataType : 'json',
			success : function(res) {
				if (res.status == 200) {
					//循环遍历json，并将其加入显示中
					//alert("退出登录成功！");
					window.location.href="/login.html";
				} else
					alert("退出登录失败！");
			},
			error : function(xml, err, throwInfo) {
				alert(err);
			}
	    });	
	});
	$(window).resize(function(){
	  	//alert($(window).height()-$("#term-show").offset().top);
	  	//selfresize();
	  	
	  });
	
  $("#richClose").click(function(){
		document.getElementById('richDiv').style.display="none";
		document.getElementById('documentMessage').style.display="";
		$("#inputCost")[0].style.display="none";
		$("#showCost")[0].style.display="inline-block";
		$("#file-upload")[0].style.display="none";
		var deleteDocBtn = document.getElementsByClassName('doc-delete'); 
		 for( i = 0; i < deleteDocBtn.length; i++ ) { 
			 deleteDocBtn.item(i).style.display = 'none'; 
		 }
		//document.body.removeChild(document.getElementsByClassName('mce-tinymce mce-container mce-panel')[0]);
  });
  
  $("#richSave").click(function(){
		 document.getElementById('richDiv').style.display="none";
		 //alert(tinymce.activeEditor.getContent());
		 var documentNodeIdDiv=document.getElementById('documentNodeIdDiv').innerHTML;
		 _jm.save_document(documentNodeIdDiv,tinymce.activeEditor.getContent());
		 document.getElementById('documentBodyDiv').innerHTML=tinymce.activeEditor.getContent();
		 document.getElementById('documentMessage').style.display="";
		 
		 
		 $("#inputCost")[0].style.display="none";
		 $("#showCost")[0].style.display="inline-block";
		 $("#showCost")[0].innerHTML=$("#inputCost")[0].value;
		 $("#file-upload")[0].style.display="none";
		 var deleteDocBtn = document.getElementsByClassName('doc-delete'); 
		 for( i = 0; i < deleteDocBtn.length; i++ ) { 
			 deleteDocBtn.item(i).style.display = 'none'; 
		 }
		 _jm.set_cost(documentNodeIdDiv,$("#inputCost")[0].value);

  });

  $("#documentClose").click(function(ev){
	 var documentDiv=document.getElementById('documentDiv');
	 documentDiv.style.display="none"; 
  });
  $("#mindmap-tool-left").click(function(ev){
	  var leftbar = document.getElementById("mindmap-tool");//.getAttribute('left');
	  var left = leftbar.offsetLeft;
	  if(left>-600){
		  leftbar.style.left=left-100+"px";
	  }
  });
  $("#mindmap-tool-right").click(function(ev){
	  var leftbar = document.getElementById("mindmap-tool");//.getAttribute('left');
	  var left = leftbar.offsetLeft;
	  if(left<0){
		  leftbar.style.left=left+100+"px";
	  }
	  
  });
  $("#documentEdit").click(function(ev){
	var documentDiv=document.getElementById('documentMessage');
	documentDiv.style.display="none"; 
	 
	
	$("#inputCost")[0].style.display="inline-block";
	$("#inputCost")[0].value=$("#showCost")[0].innerHTML;
	$("#showCost")[0].style.display="none";
	$("#file-upload")[0].style.display="inline-block";
	var deleteDocBtn = document.getElementsByClassName('doc-delete'); 
	 for( i = 0; i < deleteDocBtn.length; i++ ) { 
		 deleteDocBtn.item(i).style.display = 'inline-block'; 
	 }
	 var documentBodyDiv = document.getElementById('documentBodyDiv');
	 tinymce.activeEditor.setContent(documentBodyDiv.innerHTML);
	 
	
	 var richText = document.getElementById('richDiv');
	 richText.style.display="block";
  });
  
  $("#delete-pushpin").click(function(ev){
	  	_jm.add_revoke(); 
		 var documentDiv=document.getElementById('documentDiv');
		 documentDiv.style.display="none";
		 delete_document();
  });
  
  $('#addChildNode').click(function () {
	 
    add_child_node();
  });

  $('#addBrotherNode').click(function () {
	 
    add_brother_node();
  });
  $('#addLink').click(function () {
	
    add_link();
  });
  $('#fromidbtn').click(function () {
	  
	link_set_from();
  });
  $('#toidbtn').click(function () {
	link_set_to();
  });
  $('#removeNode').click(function () {
	 
    remove_node();
  });
  $('#cutNode').click(function () {
	 
    cut_node();
  });
  $('#addAttribute').click(function () {
	 
    add_attribute();
  });
  $('#allcost').click(function () {
	get_cost();
  });
  $('#remark').click(function () {
	 
	add_document();
  });
  $('#savefile').click(function () {
    save_nodearray_file();
  });
  $('#expend3').click(function () {
	  _jm.add_revoke(); 
	  expand_to_level3();
  });
  $('#expend2').click(function () {
	  _jm.add_revoke(); 
	  expand_to_level2();
  });
  $('#expend1').click(function () {
	  _jm.add_revoke(); 
	  expand_to_level1();
  });
  $('#changetheme').change(function () {
	 //	 alert(1);
	  var change_theme = document.getElementById("changetheme");
	  set_theme(change_theme.value);
  });
  
  $('#zoom-in').click(function(event){
	  	//var icon=document.getElementById('treaticon');
	  	//var searchtext=document.getElementById('treatsearchtext');
	  	//icon.style.display="";
	  	//searchtext.style.display="";
	  	//this.style.display="none";
  });
  $('#treatsearchsubmit').click(function(event){
	  var searchtext=document.getElementById('treatsearchtext');
		var defini=searchtext.value;
		var ss=document.getElementById('treatsearchresultall');
			var childs=ss.childNodes;
			if(!!childs){
				for(var i=childs.length-1;i>=0;i--){    
					ss.removeChild(childs.item(i));    
				}   
			}
			if(!!!defini){
	  			ss.style.display='none';
	  			return;
	  		}
	  		ss.style.display='';
		$.ajax({
				type : 'GET',
				url : '/terms/search',
			    cache: false,
				async:false,
				data :{
					"definition":defini
				},
				//timeout:7000,//请求超时后停止请求
				dataType : 'json',
				//contentType: "application/json; charset=utf-8",
				success : function(res) {
					if (res.status == 200) {
						for(var kk in res.entries){
							//alert(res.entries[kk].definition+"+"+res.entries[kk].id);
							addSearchDivForM(res.entries[kk].id,res.entries[kk].definition);
						}
						alert(res.data.definition);
					} else
						alert("添加新任务失败");
				},
				error : function(xml, err, throwInfo) {
					alert(err);
				}
    	});
		
		$.ajax({
				type : 'GET',
				url : '/schems/search',
			    cache: false,
				async:false,
				data :{
					"root":defini,
					"type":'1',
					"state":'1'
				},
				//timeout:7000,//请求超时后停止请求
				dataType : 'json',
				//contentType: "application/json; charset=utf-8",
				success : function(res) {
					if (res.status == 200) {
						for(var kk in res.entries){
							//alert(res.entries[kk].definition+"+"+res.entries[kk].id);
							
							addSearchDivForP(res.entries[kk].id,res.entries[kk].root);
							
						}
						
					} else
						alert("添加新任务失败");
				},
				error : function(xml, err, throwInfo) {
					alert(err);
				}
    	});
		//addSearchDivForClose();
  });
  
	  $('#treatsearchtext').keydown(function(event){
	  	if(event.keyCode==13){
	  		$('#treatsearchsubmit').click();
	  	} 
	  });
	  $('#tagsAddMsgDiv').click(function(event){
		  var tags_content=document.getElementById("tags-content");
		  var tagsMsgInput=document.createElement('div');
		  tagsMsgInput.setAttribute("class","tagsMsgDiv");
		  tagsMsgInput.setAttribute('contenteditable',true);
		  tags_content.appendChild(tagsMsgInput);
	  });
	  
	  $('#tags-submit').click(function(event){
		  var tagsNodeId=document.getElementById('tagsNodeIdDiv').innerHTML;
		  var tags_content="";
		  $("#tags-content .tagsMsgDiv").each(function (){
			  var tag_this = $(this)[0].innerHTML;
			  if(!!tag_this){
				  if(!!tags_content){
					  tags_content = tags_content+';'+tag_this;
				  }else{
					  tags_content = tag_this;
				  }
			  }
		  });
		  _jm.save_tags(tagsNodeId,tags_content);
	  });
	  $("#delete-tags").click(function(ev){
		 
		  _jm.add_revoke(); 
		  delete_tags();
	  });
	  $('#file-upload').click(function(){
		  uploaddocwin();
	  });
  //点击任务按钮，进行跳转，到绘制思维导图界面
  //var _jm = null;
  function GoBottom(){
	  timer=setInterval(runToBottom,1);
  }
  
  
  function runToBottom(){  
	  var heightt = $(document).height()-$(window).height()-100;
	  currentPosition=document.documentElement.scrollTop || document.body.scrollTop;
	 
	  currentPosition+=10;
	  if(currentPosition<heightt)
	  {  
		  window.scrollTo(0,currentPosition);  
	  }  
	  else
	  {  
		window.scrollTo(0,document.body.scrollHeight);  
		clearInterval(timer);  
	  }  
  } 
  function copy_document(data,id){
	   $.ajax({
			type : 'POST',
			url : '/documents/'+id+'/copy',
			async:false,
			//timeout:7000,//请求超时后停止请求
			dataType : 'json',
			success : function(res) {
			if (res.status == 200) {
					 //_jm.add_document(selected_id,res.data.id);
				data.document=res.data.id;
			} else{
				alert("创建失败");
				return;
			}},
			error : function(xml, err, throwInfo) {
				alert(err);
			}
		});
 }
  function add_data(addtoid,adddata){
	  resetId(addtoid,adddata,0,'1');
  }
  function resetLink(adddata){
	  for(var i in adddata){
		  if(!!adddata[i].link){
 			 for(var k in adddata[i].link){
 				_jm.add_link(changenode[adddata[i].id]+"link"+changenode[adddata[i].link[k].to],changenode[adddata[i].id],changenode[adddata[i].link[k].to],adddata[i].link[k].linkmsg,adddata[i].link[k].refer1x,adddata[i].link[k].refer1y,adddata[i].link[k].refer2x,adddata[i].link[k].refer2y);
 			 }
 		 }
	  }
  }
  function resetId(desId,adddata,k,changeId){
	  var data={
			 
			  };
	  if(k==0){
		  for(var i in adddata){
		    	if(adddata[i].isroot==true){
		    		data={
		    				 
					  };
		    		 maxid=(parseInt(maxid)+1).toString();
		    		 var nodeid=maxid;
		    		 if(!!adddata[i].cost){
		    			 data.cost=adddata[i].cost;
		    		 }
		    		 if(!!adddata[i].tags){
		    			 
		    			 data.tags=adddata[i].tags;
		    		 }
		    		 if(!!adddata[i].document){
		    			
		    			 copy_document(data,adddata[i].document);
		    			 
		    		 }
		    		 changenode[adddata[i].id]=nodeid;
		    		 var node = _jm.add_node(desId, nodeid,adddata[i].topic, data);
		    		 resetId(nodeid,adddata,1,adddata[i].id);
		    	}  	
		  }
	  }else{
		  for(var m in adddata){
			  	
		    	if(adddata[m].parentid===changeId){
		    		data={
		    				 
					  };
		    		 maxid=(parseInt(maxid)+1).toString();
		    		 var nodeid=maxid;
		    		 if(!!adddata[m].tags){
		    			 data.tags=adddata[m].tags;
		    		 }
		    		 if(!!adddata[m].cost){
		    			 data.cost=adddata[m].cost;
		    		 }
		    		 if(!!adddata[m].document){
		    			
		    			 copy_document(data,adddata[m].document);
		    		 }
		    		 changenode[adddata[m].id]=nodeid;
		    		 var node = _jm.add_node(desId, nodeid,adddata[m].topic, data);
		    		 resetId(nodeid,adddata,1,adddata[m].id);
		    	}  	
		  } 
	  }
  }
  function drawPGraph(jsondata) {
	    var mind = jsondata;
	    var options = {
	      container: 'jsmind_container',
	      editable: true,
	      theme: 'greensea',
	      shortcut: {
	        handles: {
	          test: function (j, e) {
	            console.log(j);
	          }
	        },
	        mapping: {
	          test: 1111
	        }
	      }
	    };
	    document.getElementById("secondbread").innerText = rootName;
	    _jm = jsMind.show(options, mind);
	    
	    //_jm.show(jsondata);
	    // jm.set_readonly(true);
	    // var mind_data = jm.get_data();
	    // alert(mind_data);  
	  }
  function addSearchDivForClose(){
	  var sra=document.getElementById('treatsearchresultall');
	  	
	  	var newresult=document.createElement('div');
	  	newresult.setAttribute("id","result-close");
	  	newresult.setAttribute("class","treatsearchresult");
	  	
	  	newresult.innerHTML="关闭";
	  	sra.appendChild(newresult);
	  	
	  	sra.style.display="";
		$('#result-close').click(function(){
			sra.innerHTML="";
			sra.style.display="none";
			var icon=document.getElementById('treaticon');
		  	var searchtext=document.getElementById('treatsearchtext');
		  	icon.style.display="none";
		  	searchtext.style.display="none";
		  	var zoom=document.getElementById('zoom-in');
		  	zoom.style.display="";
		});
  }		
  
  
  
  function addSearchDivForM(id,definition){
	  	var sra=document.getElementById('treatsearchresultall');
	  	
	  	var newresult=document.createElement('div');
	  	newresult.setAttribute("id","msearchresult-"+id);
	  	newresult.setAttribute("class","treatsearchresult");
	  	
	  	newresult.innerHTML="<div id='name-left'>"+"素材库"+"+"+definition+"</div>"+'<span id="'+"msearchresultin-"+id+'" class="glyphicon glyphicon-log-in"></span><span id="'+"msearchresultsee-"+id+'"class="glyphicon glyphicon-eye-open"></span>'+"<div style='clear:both'></div>";
	  	
	  	sra.appendChild(newresult);
	  	
	  	sra.style.display="";
	  	$('#msearchresultin-'+id).click(function(){
	  		var selected_node = _jm.get_selected_node(); // as parent of new node
	  		if (!selected_node) {
	  			prompt_info('please select a node first.');
	  		}
	  	
	  			var searchroot =Number(id);
				var select=0;
				$.ajax({
					type : 'GET',
					url : '/terms/roots/search',
				    cache: false,
					async:false,
					data :{
						"searchroot":searchroot
					},
					//timeout:7000,//请求超时后停止请求
					dataType : 'json',
					contentType: "application/json; charset=utf-8",
					success : function(data) {
						if (data.status == 200) {
							select=1;
						} else
							alert("添加新任务失败");
					},
					error : function(xml, err, throwInfo) {
						alert(err);
					}
	      	});
			if(select==1){
				
				$('#insert-search').modal('hide');
				var load=document.getElementById("load-circle");
				load.style.display="block"; 
				 $.ajax({
					    type: 'GET',
					    url: '/terms/search/draw',
					    cache :false,
					    data:{
					    	'depth':9
					    },
					    //timeout:7000,//请求超时后停止请求
					    //dataType : 'json',
					    success: function (res) {
					      if (res.status == 200) {
					    	  _jm.add_revoke(); 
					    	  add_data(selected_node.id,res.data);
					    	  load.style.display="none"; 
					      }else{
					        alert("加载失败");
					       
					      }
					    },
					    error: function (xml, err, throwInfo) {
					      alert(err);
					    }
				  });	
			}
	  	});
	  	
	  	$('#msearchresultsee-'+id).click(function(){
	  			
	  			var searchroot =Number(id);
				var select=0;
				$.ajax({
					type : 'GET',
					url : '/terms/roots/search',
				    cache: false,
					async:false,
					data :{
						"searchroot":searchroot
					},
					//timeout:7000,//请求超时后停止请求
					dataType : 'json',
					contentType: "application/json; charset=utf-8",
					success : function(data) {
						if (data.status == 200) {
							select=1;
						} else
							alert("添加新任务失败");
					},
					error : function(xml, err, throwInfo) {
						alert(err);
					}
	      	});
			if(select==1){
				
				$('#insert-search').modal('hide');
				 $.ajax({
					    type: 'GET',
					    url: '/terms/search/draw',
					    cache :false,
					    data:{
					    	'depth':9
					    },
					    //timeout:7000,//请求超时后停止请求
					    //dataType : 'json',
					    success: function (res) {
					      if (res.status == 200) {
					    	  var showsearch=document.getElementById("jsmind_container_search");
					    	  showsearch.style.display="block";
					    	  showsearch.innerHTML='<span id="closeshow" class="glyphicon glyphicon-remove" ></span>';
					    	//  alert(11);
					    	  drawSearchGraph(res.data);
					    	  document.getElementById('closeshow').addEventListener('touchstart', function(event) {
					    		  
					    		  showsearch.style.display="none";
					    		  showsearch.innerHTML='';
					    		  sra.style.display='';
					    		  var documentDiv=document.getElementById('documentDiv');
					    		  documentDiv.style.display="none"; 
					    	  });
					    	  $('#closeshow').click(function(){
					    		  showsearch.style.display="none";
					    		  showsearch.innerHTML='';
					    		  sra.style.display='';
					    		  var documentDiv=document.getElementById('documentDiv');
					    		  documentDiv.style.display="none"; 
					    		  
					    	  });
					      
					      }else{
					        alert("加载失败");
					       
					      }
					    },
					    error: function (xml, err, throwInfo) {
					      alert(err);
					    }
				  });	
			}
			sra.style.display='none';
	  	});
	  	
	  }
	  function addSearchDivForP(id,definition){
	  	
		  var sra=document.getElementById('treatsearchresultall');
		  	
		  	var newresult=document.createElement('div');
		  	newresult.setAttribute("id","psearchresult-"+id);
		  	newresult.setAttribute("class","treatsearchresult");
		  	newresult.innerHTML="<div id='name-left'>"+"方案库"+"+"+definition+"</div>"+'<span id="'+"psearchresultin-"+id+'" class="glyphicon glyphicon-log-in"></span><span id="'+"psearchresultsee-"+id+'"class="glyphicon glyphicon-eye-open"></span>'+"<div style='clear:both'></div>";
		  	sra.appendChild(newresult);
		  	
		  	sra.style.display="";
			$('#psearchresultin-'+id).click(function(){
		  		var selected_node = _jm.get_selected_node(); // as parent of new node
		  		if (!selected_node) {
		  			prompt_info('please select a node first.');
		  		}
		  	
		  			var searchroot =Number(id);
					var select=0;
					$.ajax({
						type : 'GET',
						url : '/schems/roots/search',
					    cache: false,
						async:false,
						data :{
							"searchroot":searchroot
						},
						//timeout:7000,//请求超时后停止请求
						dataType : 'json',
						contentType: "application/json; charset=utf-8",
						success : function(data) {
							if (data.status == 200) {
								select=1;
							} else
								alert("添加新任务失败");
						},
						error : function(xml, err, throwInfo) {
							alert(err);
						}
		      	});
					
				if(select==1){
					$('#insert-search').modal('hide');
					var load=document.getElementById("load-circle");
					load.style.display="block"; 
					$.ajax({
						    type: 'GET',
						    url: '/schems/search/draw',
						    cache :false,
						    //timeout:7000,//请求超时后停止请求
						    //dataType : 'json',
						    success: function (res) {
						      if (res.status == 200) {
						    	  _jm.add_revoke(); 
						    	  var jsondta=eval("(" + res.data.content + ")");
						    	  add_data(selected_node.id,jsondta.data);
						    	  load.style.display="none"; 
						      }else{
						        alert("加载失败");
						        window.location.href = "/admin/selfplib.html";
						      }
						    },
						    error: function (xml, err, throwInfo) {
						      alert(err);
						    }
					  });
				}
		  	});
		$('#psearchresultsee-'+id).click(function(){
	  			
	  			var searchroot =Number(id);
				var select=0;
				$.ajax({
					type : 'GET',
					url : '/schems/roots/search',
				    cache: false,
					async:false,
					data :{
						"searchroot":searchroot
					},
					//timeout:7000,//请求超时后停止请求
					dataType : 'json',
					contentType: "application/json; charset=utf-8",
					success : function(data) {
						if (data.status == 200) {
							select=1;
						} else
							alert("添加新任务失败");
					},
					error : function(xml, err, throwInfo) {
						alert(err);
					}
	      	});
			if(select==1){
				$('#insert-search').modal('hide');
				 $.ajax({
					    type: 'GET',
					    url: '/schems/search/draw',
					    cache :false,
					    data:{
					    	'depth':9
					    },
					    //timeout:7000,//请求超时后停止请求
					    //dataType : 'json',
					    success: function (res) {
					      if (res.status == 200) {
					    	  var jsondta=eval("(" + res.data.content + ")");
					    	 
					    	  var showsearch=document.getElementById("jsmind_container_search");
					    	  showsearch.style.display="block";
					    	  showsearch.innerHTML='<span id="closeshow" class="glyphicon glyphicon-remove" ></span>';
					    	//  alert(11);
					    	  drawSearchGraph(jsondta.data);
					    	  document.getElementById('closeshow').addEventListener('touchstart', function(event) {
					    		  
					    		  showsearch.style.display="none";
					    		  showsearch.innerHTML='';
					    		  sra.style.display='';
					    		  var documentDiv=document.getElementById('documentDiv');
					    		  documentDiv.style.display="none"; 
					    	  });
					    	  $('#closeshow').click(function(){
					    		  showsearch.style.display="none";
					    		  showsearch.innerHTML='';
					    		  sra.style.display='';
					    	  });
					      
					      }else{
					        alert("加载失败");
					       
					      }
					    },
					    error: function (xml, err, throwInfo) {
					      alert(err);
					    }
				  });	
			}
			sra.style.display='none';
	  	});
			
			
	  }
	  function drawSearchGraph(jsondata){
		  
		  var mind = {
			      meta: {
			        name: 'demo',
			        author: 'zhangyipin',
			        version: '0.2'
			      },
			      format: 'node_array',
			      data: jsondata
			    };


			    var options = {
			      container: 'jsmind_container_search',
			      editable: false,
			      theme: 'greensea',
			      shortcut: {
			        handles: {
			          test: function (j, e) {
			            console.log(j);
			          }
			        },
			        mapping: {
			          test: 1111
			        }
			      }
			    };
			    var _jmss=null;
			    _jmss = jsMind.show(options, mind);
	  }
  function drawGraph(jsondata) {
	    var mind = {
	      meta: {
	        name: 'demo',
	        author: 'zhangyipin',
	        version: '0.2'
	      },
	      format: 'node_array',
	      data: jsondata
	    };


	    var options = {
	      container: 'jsmind_container',
	      editable: true,
	      theme: 'greensea',
	      shortcut: {
	        handles: {
	          test: function (j, e) {
	            console.log(j);
	          }
	        },
	        mapping: {
	          test: 1111
	        }
	      }
	    };
	    
	    var rootId;
	    for(var i in jsondata){
	    	if(jsondata[i].isroot==true){
	    		rootId=jsondata[i].id;
	    		rootName=jsondata[i].topic;
	    	}
	    	
	    	
	    }
	    var allcount=0;
	    for(var i in jsondata){
			if(jsondata[i].parentid==rootId){
				allcount=allcount+1;
			}
		}
	    var count = 0;
	    if(allcount>3){
	    	for(var i in jsondata){
	    		if(jsondata[i].parentid==rootId&&!!!jsondata[i].direction){
	    			if(count%2==0){
	    				jsondata[i].direction="right";
	    			}else{
	    				jsondata[i].direction="left";
	    			}
	    			count=count+1;
	    		}
	    	}
	    }
	    document.getElementById("secondbread").innerText = rootName;
	    _jm = jsMind.show(options, mind);
	    //_jm.show(jsondata);
	    // jm.set_readonly(true);
	    // var mind_data = jm.get_data();
	    // alert(mind_data);  
	  }

  function get_selected_nodeid() {
    var selected_node = _jm.get_selected_node();
    if (!!selected_node) {
      return selected_node.id;
    } else {
      return null;
    }
  }


  //对各个按钮的响应,没有选中selected_id为空
  function add_child_node() {
    var data={};
    var selected_node = _jm.get_selected_node(); // as parent of new node
    if (!selected_node) {
      prompt_info('please select a node first.');
    }
    maxid=(parseInt(maxid)+1).toString();
    var nodeid=maxid;
    
    var topic = '*New Node*';
    _jm.add_revoke(); 
    var node = _jm.add_node(selected_node, nodeid, topic, data);
  }

  function add_brother_node() {
	    var data = {};
	    var selected_node = _jm.get_selected_node(); 
	    if (!selected_node) {
	      prompt_info('please select a node first.');
	    }
	    maxid=(parseInt(maxid)+1).toString();
	    var nodeid=maxid;
	    var topic = '*New Node*';
	    _jm.add_revoke(); 
	    var node = _jm.add_node(selected_node.parent, nodeid, topic, data);
  }
  function add_link() {
	  var selected_node = _jm.get_selected_node();

	  var linkInput=document.getElementById('linkInput');
	  //link_input.style.display="none";
	  
	  if(linkInput.style.display!="none"){
		  if(!!fromid&&!!toid){
			  _jm.add_revoke();
			  _jm.add_link(fromid+'link'+toid,fromid,toid,linkmsg,100,100,100,100);
			  
			  fromid="";
			  toid="";
			  var fromInput=document.getElementById('fromid');
			  fromInput.innerHTML="";
			  var toInput=document.getElementById('toid');
			  toInput.innerHTML="";
		  }else{
			  fromid="";
			  toid="";
			  var fromInput=document.getElementById('fromid');
			  fromInput.innerHTML="";
			  var toInput=document.getElementById('toid');
			  toInput.innerHTML=""; 
		  }
		  linkInput.style.display="none";
	  }else{
		  if (!!selected_node) {
			  var fromInput=document.getElementById('fromid');
			  fromInput.innerHTML=selected_node.topic;
			  fromid=selected_node.id;
			  
		  }
		  linkInput.style.display="";
	  } 
	  
  }
  function link_set_from() {
	  var selected_node = _jm.get_selected_node();
	  if (!!selected_node) {
		  var fromInput=document.getElementById('fromid');
		  fromInput.innerHTML=selected_node.topic;
		  fromid=selected_node.id;
		  
	  }
  }
  function link_set_to() {
	  var selected_node = _jm.get_selected_node();
	  if (!!selected_node) {
		  var toInput=document.getElementById('toid');
		  toInput.innerHTML=selected_node.topic;
		  toid=selected_node.id;
		  
	  }
  }
  
  function add_attribute() {
	  var selected_id = get_selected_nodeid();
	  
	  if(!!selected_id){
		  _jm.add_revoke();
		  _jm.add_attribute(selected_id);
	  }
  }
  
  function add_document(){
	  var selected_id = get_selected_nodeid();
	  //create document
	  var selected_node = _jm.get_selected_node();
	  if(!!selected_node.data['document']){
		  alert(selected_node.data['document']);
	  }else{
		  $.ajax({
				type : 'POST',
				url : '/documents',
				async:false,
				//timeout:7000,//请求超时后停止请求
				dataType : 'json',
				success : function(res) {
				if (res.status == 200) {
					 _jm.add_revoke(); 
					 _jm.add_document(selected_id,res.data.id);
				} else{
					alert("创建失败");
				}},
				error : function(xml, err, throwInfo) {
					alert(err);
				}
			});
	  }
  }
  function delete_document(){
	  var selected_id = $("#documentNodeIdDiv").html();
	  _jm.delete_document(selected_id);
	  //create document
	 
  }
  function delete_tags(){
	  var tagsNodeId=document.getElementById('tagsNodeIdDiv').innerHTML;
	  _jm.delete_tags(tagsNodeId);
	  //create document
	 
  }
  function remove_node() {
		 var selected_link= _jm.get_selected_link()
		//var isnode=_jm.view.is_node()
		 if(!!selected_link){
			 
			 //alert(selected_link.id);
			 _jm.add_revoke();
			 _jm.remove_link(selected_link.id);
		 }
		
		 var selected_id = get_selected_nodeid();
		 if(!!selected_id){
			 //alert(selected_id);
			 _jm.add_revoke();
			 _jm.remove_node(selected_id);
		 }
  }
  function cut_node() {
	  var selected_id = get_selected_nodeid();
	  if (!selected_id) {
		  prompt_info('please select a node first.');
	  }
	  _jm.add_revoke(); 
	  _jm.cut_node(selected_id);
  }
  function save_nodearray_file(){
	 
	  var mind_data = _jm.get_data('node_array');
      var mind_name = mind_data.meta.name;
      for(var ll in mind_data.data){
    	  
    	  if(mind_data.data[ll].tags=="true"){
    		  mind_data.data[ll].tags="";
    	  }
    	  if(mind_data.data[ll].isroot==true){
    		  rootName=mind_data.data[ll].topic;
    	  }
      }
      var mind_str = jsMind.util.json.json2string(mind_data);
      
      var jsondata = {
  			"root" : rootName,
  			"account_id":account_id,
  			"content":mind_str ,
  			"state":"0",
  			"type":"1",
  			"theme":_jm.get_theme()
  		};
  		$.post("/schems/save",jsondata).success(function(res) {
  			if (res.status == 200) {
  				alert('保存成功！！！');
  				window.location.href = "/admin/selfplib.html";
  			} else{
  				alert("保存失败！！");
  			}
  		}).error(function(xml, err, throwInfo) {
  			alert(err);
  		});
      
  }
  function expand_to_level3(){
      _jm.expand_to_depth(3);
  }
  function get_cost(){
	  var selected_id = get_selected_nodeid();
	  if(!!selected_id){
		  $("#costAll")[0].innerHTML=_jm.get_cost(selected_id);
	  }else{
		  $("#costAll")[0].innerHTML="未选择节点！";
	  }
	   
  }
  function expand_to_level2(){
      _jm.expand_to_depth(2);
  }  
  function expand_to_level1(){
      _jm.expand_to_depth(1);
  }
  function set_theme(theme_name){
      _jm.set_theme(theme_name);
  }
  function selfresize(){
	  //e.preventDefault();
	//  if(window.location.pathname=='/admin/selfmtreat.html'){
		if(($(window).width()-35)<500){
	  		$('#documentDiv').css('max-width',$(window).width()-35+'px'); 
	  	}else{
	  		$('#documentDiv').css('max-width',500+'px'); 
	  	}
	  	 $('#documentDiv').css('max-height',$(window).height()*0.9-30+'px');
	     
	  
	  	  $('#treatsearchresultall').css('max-height',$(window).height()-$("#jsmind_container").offset().top+'px');
		  if($(window).width()<1280){
			$('.mindmap-main').css('width','100%');
			$('.function-bar').css('width','100%');
			
			$('#path-group').css('margin-left','10px');
			$('#user-message').css('margin-right','10px');
			$('#mindmap-tool button').css('font-size','7px');
			$('#mindmap-tool button').css('margin-left','5px');
			$('#mindmap-tool button').css('padding','2px 4px');
			$('#changetheme').css('height','26px');
			$('#changetheme').css('width','110px');
			$('#changetheme').css('font-size','10px');
			$('#changetheme').css('padding','2px 4px');
			$('#treatsearch').css('height','25px');
			
			
			$('#treaticon').css('top','7px');
			$('#treatsearchtext').css('width','130px');
			$('#treatsearchresultall').css('font-size','10px');
			$('#treatsearchresultall').css('min-width','150px');
			$('#treatsearchresultall').css('top','94%');
			$('#jsmind_container').width('100%');
			$('#jsmind_container').css('height',$(window).height()-$("#jsmind_container").offset().top+'px');
			$('#jsmind_container_search').css('height',$('#jsmind_container').height()+'px');
			$('#jsmind_container_search').css('margin-top',-$('#jsmind_container').height()+'px');
			
		
		}else{
			$('.mindmap-main').css('width','85%');
			$('.function-bar').css('width','85%');
			$('#jsmind_container').width('85%');
			$('#path-group').css('margin-left','50px');
			$('#user-message').css('margin-right','80px');
			$('#mindmap-tool button').css('font-size','14px');
			$('#mindmap-tool button').css('padding','6px 12px');
			$('#changetheme').css('height','53px');
			$('#changetheme').css('width','150px');
			$('#changetheme').css('font-size','20px');
			$('#changetheme').css('padding','6px 12px');
			$('#treatsearch').css('height','50px');
			$('#treatsearchresultall').css('top','85%');

			$('#treaticon').css('top','16px');
			$('#treatsearchtext').css('width','200px');
			$('#treatsearchresultall').css('font-size','14px');
			$('#treatsearchresultall').css('min-width','180px');
			$('#jsmind_container').css('height',$(window).height()-$("#jsmind_container").offset().top+'px');
			$('#jsmind_container_search').css('height',$('#jsmind_container').height()+'px');
			$('#jsmind_container_search').css('margin-top',-$('#jsmind_container').height()+'px');
		}
		
		if(!!$('#jsmind-inner').width()){
			var xd=$('#jsmind_container').width()-fx;
			var yd=$('#jsmind_container').height()-fy;
			
			fx=$('#jsmind_container').width();
			fy=$('#jsmind_container').height();
			$('#jsmind-inner').css('left',parseFloat($('#jsmind-inner').css('left').replace('px',''))+parseFloat(xd/2)+'px');
			$('#jsmind-inner').css('top',parseFloat($('#jsmind-inner').css('top').replace('px',''))+parseFloat(yd/2)+'px');
			
		}
		
	  //}
		//alert($('#jsmind-inner').width());
		//$('#jsmind-inner').css('left',-($('#jsmind-inner').width()-$('#jsmind_container').width())/2+'px');
        //$('#jsmind-inner').css('top',-($('#jsmind-inner').height()-$('#jsmind_container').height())/2+'px');
		//fx=$('#jsmind_container').width();
		//fy=$('#jsmind_container').height();
  }
  
  function uploaddocwin(){
	  	var hidebg=document.createElement("div");
	  	hidebg.setAttribute('id','my-mce-modal-block'); 
	  	 
	  	hidebg.setAttribute('class','mce-reset mce-fade mce-in'); 
	  	hidebg.style.display="block"; 	
	  	document.body.appendChild(hidebg);
	  	var myform=document.createElement("div");
	  	myform.setAttribute('class','my-form');
	  	myform.setAttribute('id','my_form1');
	  	var myinput=document.createElement("input");
	  	myinput.setAttribute('type','file');
	  	myinput.setAttribute('accept',' application/pdf,'+//text/plain,
	  			' application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document,'+
	  			' application/vnd.ms-powerpoint, application/vnd.openxmlformats-officedocument.presentationml.presentation,'+
	  			' application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	  	
	  	myinput.setAttribute('class','file-loading');
	  	myinput.setAttribute('id','newDocFile');
	  	myform.appendChild(myinput);
	  	myform.style.display="block";
	  	document.body.appendChild(myform);
	  	//var upimg=document.getElementById("my_form");
	  	//upimg.style.display="block";
	  	$(document).keydown(function(event){
	  		if(event.keyCode == 27){
	  			var upimg1=document.getElementById("my_form1");
	      		document.body.removeChild(upimg1);
	          	var hidebg1=document.getElementById('my-mce-modal-block');
	      		document.body.removeChild(hidebg1);
	  		}
	  	});
	  	var documentIdDiv=document.getElementById('documentIdDiv').innerHTML;
	  	$("#newDocFile").fileinput({
	      	  language: 'zh', //设置语言
	          uploadUrl:  "/document/upload/doc/"+documentIdDiv, //上传的地址
	          allowedFileExtensions : [],//接收的文件后缀
	          previewFileType: "image",
	          browseClass: "btn btn-primary", //按钮样式             
	          enctype: 'multipart/form-data',
	          showRemove: false, //是否显示上传按钮
	    //      showUpload: false, //是否显示上传按钮
	          showClose: false,
	      })
	      .on("fileuploaded", function(event, data) {
	      	if(data.response.status==200)
	      	{
	      		var upimg=document.getElementById("my_form1");
	      		document.body.removeChild(upimg);
	          	var hidebg=document.getElementById('my-mce-modal-block');
	      		document.body.removeChild(hidebg);
	      		var doc_id = data.response.data.id;
	      		var doc_name = data.response.data.src;
	      		alert("上传成功！！"+doc_name);
	      		addDocumentFile(doc_id,doc_name);
	      	}else{
	      		alert("上传失败！！");	
	      	}
	      });
	  	$('#my-mce-modal-block').click(function(event){
	  		var upimg1=document.getElementById("my_form1");
      		document.body.removeChild(upimg1);
          	var hidebg1=document.getElementById('my-mce-modal-block');
      		document.body.removeChild(hidebg1);
	      });
	  } 


  function addDocumentFile(doc_id,doc_name){
	  var newDocFile=document.getElementById("documentDocDiv");
	  var newDocDiv=document.createElement("div");
	  var newDocSpan=document.createElement("span");
	  var newDocDelete=document.createElement("span");
	  newDocDelete.setAttribute('id',"doc-delete-"+doc_id);
	  newDocDiv.setAttribute('id',"doc-file-"+doc_id);
	  newDocDelete.setAttribute('class',"btn glyphicon glyphicon-trash doc-delete");
	  newDocDelete.style.display="inline-block";
	  newDocSpan.innerHTML="<a href=/document/download/doc/"+doc_id+">"+doc_name+"</a>           ";//+"<span class='glyphicon glyphicon-trash'></span>";
	  newDocSpan.appendChild(newDocDelete);
	  newDocDiv.appendChild(newDocSpan);
	  newDocFile.appendChild(newDocDiv);
	  
	  var documentId=document.getElementById('documentIdDiv').innerHTML;
	  
	  $('#doc-delete-'+doc_id).click(function(){
		  var jsondata={
				  "documentid":documentId,
				  "docid":doc_id,
			};
		  
		  $.ajax({
				type : 'GET',
				 url: '/document/delete/doc',
			    cache: false,
				async:false,
				data :{
					"documentid":documentId,
					"docid":doc_id,
		  	      },
				//timeout:7000,//请求超时后停止请求
				dataType : 'json',
				contentType: "application/json; charset=utf-8",
				success : function(data) {
					if (data.status == 200) {
						newDocDiv.removeChild(newDocSpan);
					} else
						alert("添加新任务失败");
				},
				error : function(xml, err, throwInfo) {
					alert(err);
				}
    	  });
	  });
}
  
  
  function uploadwin(){
	  	var hidebg=document.createElement("div");
	  	hidebg.setAttribute('id','my-mce-modal-block'); 
	  	 
	  	hidebg.setAttribute('class','mce-reset mce-fade mce-in'); 
	  	hidebg.style.display="block"; 	
	  	document.body.appendChild(hidebg);
	  	var myform=document.createElement("div");
	  	myform.setAttribute('class','my-form');
	  	myform.setAttribute('id','my_form');
	  	var myinput=document.createElement("input");
	  	myinput.setAttribute('type','file');
	  	myinput.setAttribute('accept','image/*,video/mp4');
	  	myinput.setAttribute('class','file-loading');
	  	myinput.setAttribute('id','newImage');
	  	myform.appendChild(myinput);
	  	myform.style.display="block";
	  	document.body.appendChild(myform);
	  	//var upimg=document.getElementById("my_form");
	  	//upimg.style.display="block";
	  	$(document).keydown(function(event){
	  		if(event.keyCode == 27){
	  			var upimg1=document.getElementById("my_form");
	      		document.body.removeChild(upimg1);
	          	var hidebg1=document.getElementById('my-mce-modal-block');
	      		document.body.removeChild(hidebg1);
	  		}
	  	});
	  	$("#newImage").fileinput({
	      	language: 'zh', //设置语言
	          uploadUrl:  "/document/image", //上传的地址
	        //  allowedFileExtensions : ['jpg', 'png','gif'],//接收的文件后缀
	          previewFileType: "image",
	          browseClass: "btn btn-primary", //按钮样式             
	          enctype: 'multipart/form-data',
	          showRemove: false, //是否显示上传按钮
	    //      showUpload: false, //是否显示上传按钮
	          showClose: false,
	      })/*
	      .on("filebatchselected", function(event, files) {
	          $(this).fileinput("upload");
	      })*/
	      
	      .on("fileuploaded", function(event, data) {
	      	//alert(JSON.stringify(data));
	      	if(data.response.status==200)
	      	{
	      		alert("上传成功！！");
	      		var upimg=document.getElementById("my_form");
	      		document.body.removeChild(upimg);
	          	var hidebg=document.getElementById('my-mce-modal-block');
	      		document.body.removeChild(hidebg);
	      		var src = data.response.data.src;
	      		var mysrc=src;//"http://www.jingyanbus.com/uploads/150307/4175-15030GFS02a.jpg";
	      		
	      		var pathtext = document.getElementsByClassName('mce-textbox')[0];
	      		pathtext.value=mysrc;
	      		//tinymce.activeEditor.setContent(tinymce.activeEditor.getContent()+"<img src='"+mysrc+"' data-mce-src='"+mysrc+"'>");
	      		//tinymce.activeEditor.insertLink("http://www.baidu.com", "百度");

	      		//tinymce.activeEditor.insertImage(mysrc,100,100);
	      	}else{
	      		alert("上传失败！！");
	      		
	      	}
	      	
	      	//alert(JSON.stringify(data));
	      });
	  	
	  	$('#my-mce-modal-block').click(function(event){
	  		var upimg1=document.getElementById("my_form");
      		document.body.removeChild(upimg1);
          	var hidebg1=document.getElementById('my-mce-modal-block');
      		document.body.removeChild(hidebg1);
	      });
	  }
  
});
